package com.ly.juc;

/**
 * @Classname ThreadInterceptor
 * @Description TODO
 * @Date 2021/1/23 16:18
 * @Author 冷心影翼
 */
public class TestThreadInterrupt {

    private volatile boolean flag = false;



    public static void main(String[] args) throws InterruptedException {
        TestThreadInterrupt testThreadInterrupt = new TestThreadInterrupt();
//        testThreadInterrupt.execByVolatile();
        testThreadInterrupt.execByInterrupt();
    }


    public void execByVolatile() {
        Thread thread = new Thread( () -> {
            while (!flag) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {

                }
                System.out.println("do ---");
            }
        });
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopByVolatile();
    }

    public void stopByVolatile() {
        flag = true;
    }

    public void execByInterrupt() throws InterruptedException {
        Thread thread = new Thread( ()-> {
            while (!Thread.currentThread().isInterrupted() ) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    System.out.println("interrupt");
                    Thread.currentThread().interrupt();
                }
                System.out.println("do ---");
            }
        });
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}
